package com.wbao.dianniu.customView;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.DynamicDrawableSpan;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.widget.EditText;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.wbao.dianniu.data.KnowImageData;
import com.wbao.dianniu.emojiUtils.DisplayUtils;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.utils.JsonUtil;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Administrator on 20/8/31.
 */
@SuppressLint("AppCompatCustomView")
public class PictureAndTextEditorView extends EditText {

    private final String TAG = "PATEditorView";
    private static Context mContext;
//    private List<String> mContentList;

    public static final String mBitmapStart = "{\"image\":\"";
    public static final String mBitmapMH = "\"";
    public static final String mBitmapSplit = ",";
    public static final String mBitmapWidth = "\"imgWidth\":";
    public static final String mBitmapHeight = "\"imgHeight\":";
    public static final String mBitmapEnd = "}";
    public static String mNewLineTag = "\n";

    public PictureAndTextEditorView(Context context) {
        super(context);
        init(context);
    }

    public PictureAndTextEditorView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public PictureAndTextEditorView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        mContext = context;
//        mContentList = getmContentList();
//        insertData();
    }

    /**
     * 设置数据
     */
    /*private void insertData() {
        if (mContentList.size() > 0) {
            for (String str : mContentList) {
                if (str.indexOf(mBitmapStart) != -1) {//判断是否是图片地址
                    insertUriBitmap(str, getText().length(), this);
                } else {
                    //插入文字
                    SpannableString ss = new SpannableString(str);
                    append(ss);
                }
            }
        }
    }*/
    private KnowImageData praseUrl(String url) {
        KnowImageData imageData = JsonUtil.toObject(url, KnowImageData.class);
        if (null == imageData) {
            return new KnowImageData();
        }
        imageData.content = url;
        imageData.type = 2;
        return imageData;
    }

    public void insertBitmap(String path, String uploadName) {
        int index = this.getSelectionStart();
        // 获取光标所在位置
        Editable edit_text = this.getEditableText();
        SpannableString newLine = new SpannableString("\n");
        edit_text.insert(index, newLine);//插入图片前换行

        Bitmap loadedImage = BitmapFactory.decodeFile(path);
        // 得到原图的宽高值
        String tempUrl = mBitmapStart + uploadName + mBitmapMH + mBitmapSplit + mBitmapWidth + loadedImage.getWidth() + mBitmapSplit + mBitmapHeight + loadedImage.getHeight() + mBitmapEnd;
        //  图片显示的宽度为控件的宽度减去左右间隙宽度，不减左右间隙会显示两张一样的图片
        int d_width = this.getWidth() - this.getPaddingRight() - this.getPaddingLeft();
        //  根据宽度，算出图片的等比高度
        int d_height = d_width * loadedImage.getHeight() / loadedImage.getWidth();
        loadedImage = Bitmap.createScaledBitmap(loadedImage, d_width, d_height, false);
//        ImageSpan imageSpan = new ImageSpan(mContext, loadedImage);
        CustomImageSpan imageSpan = new CustomImageSpan(mContext, loadedImage);
        SpannableString spannableString = new SpannableString(tempUrl);
        spannableString.setSpan(imageSpan, 0, tempUrl.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 将选择的图片追加到EditText中光标所在位置
        index = this.getSelectionStart();
        if (index < 0 || index >= edit_text.length()) {
            edit_text.append(spannableString);
        } else {
            edit_text.insert(index, spannableString);
        }
        edit_text.insert(index + spannableString.length(), "\n");

    }

    /**
     * 插入网络图片
     *
     * @param url 图片的网络地址
     * @return
     */
    public void insertUriBitmap(final String url, final int index, final PictureAndTextEditorView mActivity) {
        KnowImageData imageData = praseUrl(url);
        Glide.with(mContext)
                .load(GlobalContext.cdndownUrl + imageData.image)
                .asBitmap()
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                        /*Editable edit_text = getEditableText();
                        //  图片显示的宽度为控件的宽度减去左右间隙宽度，不减左右间隙会显示两张一样的图片
                        int d_width = mActivity.getWidth() - mActivity.getPaddingRight() - mActivity.getPaddingLeft() - 40;

                        //  根据宽度，算出图片的等比高度
                        int d_height = d_width * bitmap.getHeight() / bitmap.getWidth();
                        bitmap = Bitmap.createScaledBitmap(bitmap, d_width, d_height, false);

                        // 根据Bitmap对象创建ImageSpan对象
//                        ImageSpan imageSpan = new ImageSpan(mContext, bitmap);
                        CustomImageSpan imageSpan = new CustomImageSpan(mContext, bitmap);
                        SpannableString spannableString = new SpannableString(url);
                        // 用ImageSpan对象替换你指定的字符串
                        spannableString.setSpan(imageSpan, 0, url.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        System.out.println("know====" + index + " |" + edit_text.length());

                        // 将选择的图片追加到EditText中光标所在位置
                        if (index < 0 || index >= edit_text.length()) {
                            edit_text.append(spannableString);
                        } else {
                            edit_text.insert(index, spannableString);
                        }*/
                    }
                });
    }


    public void insertContent(final List<String> urls, final int index, final PictureAndTextEditorView mActivity){
        if(index >= urls.size()){
            return;
        }
        final String url = urls.get(index);

        if (url.indexOf(PictureAndTextEditorView.mBitmapStart) != -1) {//判断是否是图片地址

            KnowImageData imageData = praseUrl(url);
            Glide.with(mContext)
                    .load(GlobalContext.cdndownUrl + imageData.image)
                    .asBitmap()
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                            Editable edit_text = getEditableText();
                            //  图片显示的宽度为控件的宽度减去左右间隙宽度，不减左右间隙会显示两张一样的图片
                            int d_width = mActivity.getWidth() - mActivity.getPaddingRight() - mActivity.getPaddingLeft();

                            //  根据宽度，算出图片的等比高度
                            int d_height = d_width * bitmap.getHeight() / bitmap.getWidth();
                            bitmap = Bitmap.createScaledBitmap(bitmap, d_width, d_height, true);

                            // 根据Bitmap对象创建ImageSpan对象
//                        ImageSpan imageSpan = new ImageSpan(mContext, bitmap);
                            CustomImageSpan imageSpan = new CustomImageSpan(mContext, bitmap);
                            SpannableString spannableString = new SpannableString(url);
                            // 用ImageSpan对象替换你指定的字符串
                            spannableString.setSpan(imageSpan, 0, url.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                            int position = edit_text.length();
                            // 将选择的图片追加到EditText中光标所在位置
                            if (position < 0 || position >= edit_text.length()) {
                                edit_text.append(spannableString);
                            } else {
                                edit_text.insert(position, spannableString);
                            }
                            insertContent(urls,index + 1, mActivity);
                        }
                    });

        } else {
            //插入文字
            SpannableString ss = new SpannableString(url);
            mActivity.append(ss);
            insertContent(urls,index + 1, mActivity);
        }


    }




    private SimpleTarget target = new SimpleTarget<Bitmap>() {
        @Override
        public void onResourceReady(Bitmap bitmap, GlideAnimation glideAnimation) {
            // do something with the bitmap
            // for demonstration purposes, let's just set it to an ImageView

        }
    };

    /**
     * 用集合的形式获取控件里的内容
     *
     * @return
     */
    /*public List<String> getmContentList() {
        if (mContentList == null) {
            mContentList = new ArrayList<String>();
        }
        String content = getText().toString().replaceAll(mNewLineTag, "");
        if (content.length() > 0 && content.contains(mBitmapStart)) {
            String[] split = content.split(mBitmapStart);
            mContentList.clear();
            for (String str : split) {
                mContentList.add(str);
            }
        } else {
            mContentList.add(content);
        }

        return mContentList;
    }*/

    /**
     * 设置显示的内容集合
     * <p>
     * //     * @param contentList
     */
//    public void setmContentList(List<String> contentList) {
//        if (mContentList == null) {
//            mContentList = new ArrayList<>();
//        }
//        this.mContentList.clear();
//        this.mContentList.addAll(contentList);
//        insertData();
//    }

    /*public List<String> processList(String content) {
        List<String> list = new ArrayList<>();
        if (TextUtils.isEmpty(content)) {
            return list;
        }
        int index = 0;
        int start = 0;
        while (content.indexOf(mBitmapStart, start) >= 0) {
            index = content.indexOf(mBitmapStart, start);
            String value = content.substring(index + mBitmapStart.length(), content.indexOf(mBitmapEnd, start));
            if (index >= 0) {
                list.add(content.substring(start, index));
            }
            list.add(mBitmapStart + value + mBitmapEnd);
            start = index + mBitmapStart.length() + value.length() + mBitmapEnd.length();
        }
        list.add(content.substring(start, content.length()));
        return list;
    }*/


    float oldY = 0;

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                oldY = event.getY();
                requestFocus();
                break;
            case MotionEvent.ACTION_MOVE:
                float newY = event.getY();
                if (Math.abs(oldY - newY) > 20) {
                    clearFocus();
                }
                break;
            case MotionEvent.ACTION_UP:
                break;
            default:
                break;
        }
        return super.onTouchEvent(event);
    }

    // 根据路径获得图片并压缩，返回bitmap用于显示
    public static Bitmap getSmallBitmap(String filePath, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
        DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
        int w_screen = dm.widthPixels;
        int w_width = w_screen;
        int b_width = bitmap.getWidth();
        int b_height = bitmap.getHeight();
        int w_height = w_width * b_height / b_width;
        bitmap = Bitmap.createScaledBitmap(bitmap, w_width, w_height, true);
        return bitmap;
    }

    //计算图片的缩放值
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

//        if (height > reqHeight || width > reqWidth) {
//            final int heightRatio = Math.round((float) height / (float) reqHeight);
//            final int widthRatio = Math.round((float) width / (float) reqWidth);
//            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
//        }
        // 压缩到宽度一样
        int widthRatio = Math.round((float) width / (float) reqWidth);
        inSampleSize = widthRatio;
        return inSampleSize;
    }

}
